<template>
	<view class="chat-history">
		<view class="history_content">
			<view>历史</view>
			<uv-text :lines="1" :text="fill" customStyle="opacity: 0;"></uv-text>
			<view style="display: flex;justify-content: space-between;align-items: center;">
				<view style="display: flex;justify-content: flex-start;align-items: center;">
					<i class="el-icon-coin"></i>
					<view v-if="footers" style="transition: width 2s;margin-left: 10px;">层级视图</view>
				</view>
				<view class="cursor-pointer"
					style=";display: flex;justify-content: flex-start;align-items: center;margin-left: 10px;"
					@click="multiple = !multiple">
					<i class="el-icon-edit"></i>
					<view v-if="footers" style="transition: width 2s;margin-left: 10px;">批量操作</view>
				</view>
			</view>
		</view>
		<view :class="multiple?'mid_m footer_s infinite-list':'mid_d footer_s infinite-list' "
			v-infinite-scroll="loadMore">
			<view v-for="(item,index) in data" :key="item._id || index" @mouseenter="cindex =index"
				@mouseleave="cindex = '-1'">
				<view :class="ind.includes(item._id)?'footer_item activity':'footer_item'" style="">
					<view class="positionss" @click="submit(item)">
						<uv-image :showLoading="true" :observeLazyLoad="true" :lazy-load="true" v-if="title!='对话'"
							:src="uv_image(item)" width="120" height="120" radius="5px">
							<template v-slot:loading>
								<uv-loading-icon color="red"></uv-loading-icon>
							</template>
							<template v-slot:error>
								<uv-image class="custom-loading" :observeLazyLoad="true" :lazy-load="true" width="120"
									height="120" :src="item.discordImage?item.discordImage:'/'" radius="5px">
									<template v-slot:loading>
										<uv-loading-icon color="red"></uv-loading-icon>
									</template>
									<template v-slot:error>
										<view v-if="item.state=='ON_QUEUE'||item.status=='ON_QUEUE'"
											style="display: flex;flex-direction: column;align-items: center">
											<view style="font-size: 13px;">生成中</view>
										</view>
										<view v-else>
											<view v-if="uv_image(item) == '/'"
												style="display: flex;flex-direction: column;align-items: center">
												<view style="font-size: 13px;">生成失败</view>
												<view style="font-size: 13px;color: #666;">建议删除</view>
											</view>
											<view v-else
												style="display: flex;flex-direction: column;align-items: center">
												<view style="font-size: 13px;">加载失败</view>
												<view style="font-size: 12px;color: #666;">可能资源已过期</view>
											</view>
										</view>

									</template>
								</uv-image>
							</template>
						</uv-image>
						<uv-image v-else src="/" width="40" height="40" radius="5px">
							<template v-slot:error>
								<view style="font-size: 24rpx;">{{title}}
								</view>
							</template>
						</uv-image>
						<uv-text style="width: 80px;" v-if="title=='对话'" :lines="assembly?'1':'2'"
							:text="titleName(item)">{{titleName(item)}}</uv-text>
						<view :class="$uv.os() != 'windows'||cindex==index||multiple?'':'opacity'"
							style="position: absolute;top:8px;right:8px;background-color:rgba(255, 255, 255, 0.8);border-radius: 3px;">
							<el-popconfirm v-if="!multiple" confirm-button-text='确认' icon="el-icon-info"
								icon-color="red" title="确定删除吗？" @confirm="delx(item._id)">
								<view slot="reference" style="cursor: pointer;">
									<uv-icon name="trash" style="padding: 3px 4px ;"></uv-icon>
								</view>
							</el-popconfirm>

							<view v-if="multiple" @click.stop="select(item._id)"
								style="cursor: pointer;padding: 1px 4px;border-radius: 3px;background-color:rgba(255, 255, 255, 1);border: 1px solid #333333">
								<i :class="ind.includes(item._id)?'el-icon-check':' el-icon-plus'" :style="ind.includes(item._id)?'color: #000;':'color: #fff;'"></i>
							</view>
						</view>
					</view>
				</view>
			</view>
		</view>
		<view v-if="multiple" :class="ind[0]?'multiple_h multiple_activity':'multiple_h'">
			<el-button style="display: flex;" size="mini" type="info" icon="el-icon-download" :circle="!footers">
				<view v-if="footers">下载</view>
			</el-button>
			<el-button style="display: flex;" size="mini" type="warning" icon="el-icon-star-off" :circle="!footers">
				<view v-if="footers">收藏</view>
			</el-button>
			<el-button style="display: flex;" size="mini" type="danger" icon="el-icon-delete" :circle="!footers"
				@click="delx()">
				<view v-if="footers">删除所选</view>
			</el-button>
		</view>
		<uv-toast ref="toast"></uv-toast>
		<!-- <uv-button v-else type="primary" size="small" :text="' 清除所有'+title" icon="trash"
			@click="delOtherAll"></uv-button> -->
	</view>
</template>

<script>
	// 引入
	import config from '@/common/config'
	import {
		scroll,
		delScroll,
		getScroll
	} from '@/common/api.js';
	import {
		uv_image
	} from '@/common/fun.js';
	export default {
		components: {
			// 注册组件
		},
		props: {
			assembly: Boolean,
			footers: {
				type: Boolean,
				default: false,
			},
			title: String,
			refresh: String,
			shareId: String,
		},
		data() {
			return {
				img: config.img,
				fill: config.fill,
				preloadData: {},
				pageSize: 30,
				page: 1,
				total: null, //总条数
				status: 'loadmore',
				loading: false,
				loadingText: '正在加载...',
				loadmoreText: '加载更多',
				nomoreText: '没有更多了',
				// title: '对话',
				scrollTop: 0,
				ind: [],
				data: [],
				multiple: false,
				cindex: -1,
			}
		},
		computed: {
			// uvImage(e, T) {
			// 	console.log(e, T);
			// 	return this['vuex_' + this.type + '_id'];
			// }
		},
		onPageScroll(e) {
			this.scrollTop = e.scrollTop;
			// #ifdef APP-NVUE
			this.scrollTop = e.detail.scrollTop;
			// #endif
		},
		watch: {
			// 监听data数据的变化
			multiple(newVal, oldVal) {
				this.ind = [];
			},
			refresh(newVal, oldVal) {
				this.getVuex(true);
			},
			shareId: {
				handler(newVal) {
					this.ind = [newVal];
				},
				immediate: true
			},
			// footers: {
			// 	handler(newVal) {
			// 		var that = this;
			// 		if (this.page < 4) {
			// 			setTimeout(function() {
			// 				that.loadMore();
			// 			}, 1000);
			// 		}
			// 	},
			// 	immediate: true
			// },
		},
		created() {
			// // 使用示例
			// const data = {user: {name: 'Alice',age: 25}};
			// this.observe(data); // 开始深度观察
			// // data.user.age = 30;
			this.type = this.pages();
		},
		methods: {
			titleName(e) {
				if (e.type == "fusion") {
					return e.name || "新建文章";
				} else {
					let name = null,
						tit = null;
					if ((e.content && e.content[0] && e.content[0].content) || (e.task && JSON.parse(e.task.taskInfo
								.messages)[
								0]
							.content)) {
						tit = e.content[0].content;
						if (!tit) {
							tit = JSON.parse(e.task.taskInfo.messages)[0].content;
						}
						if (typeof tit === 'string') {
							name = tit;
						} else {
							name = tit[0].text
						}
					} else {
						name = '新建' + this.title;
					}

					// console.log(JSON.parse(e.task.taskInfo.messages)[0].content == e.content[0].content, JSON.parse(e.task
					// 		.taskInfo.messages)[0].content, e.content[0]
					// 	.content);
					return name;
				}
			},
			uv_image,
			defineReactive(data, key, val) {
				var that = this;
				this.observe(val); // 递归观察子属性

				Object.defineProperty(data, key, {
					enumerable: true,
					configurable: true,
					get: function reactiveGetter() {
						return val;
					},
					set: function reactiveSetter(newVal) {
						if (newVal === val) return;
						console.log(`属性 ${key} 已经发生变化，新值为: ${newVal}`);
						val = newVal;
						that.observe(newVal); // 如果新值是个对象，则递归观察
					}
				});
			},
			observe(data) {
				var that = this;
				if (typeof data !== 'object' || data === null) {
					return;
				}
				Object.keys(data).forEach(key => {
					that.defineReactive(data, key, data[key]);
				});
			},
			pages() {
				var pages = getCurrentPages() // 获取栈实例
				let currentRoute = pages[pages.length - 1].route; // 获取当前页面路由
				let currentPage = pages[pages.length - 1]['$page']['fullPath'] //当前页面路径(带参数)
				return currentPage.split('/')[2];
			},
			loadMore() {
				this.$nextTick(() => {
					uni.$uv.throttle(this.toNext, 500, true)
				});
				// // 增加加载锁防止重复请求
				// if (this.loading || this.status !== 'loadmore') return

				// this.$nextTick(() => {
				// 	uni.$uv.throttle(() => {
				// 		this.loading = true
				// 		this.toNext().finally(() => this.loading = false)
				// 	}, 500, true)
				// })
			},
			async toNext() {
				var that = this;
				if (this.loading || this.status !== 'loadmore') return;
				this.loading = true;
				try {
					// console.log('加载中。。。');
					await this.getVuex();
				} catch (error) {
					console.error('请求失败:', error);
					this.$refs.toast.show({
						message: '加载失败，请重试',
						type: 'error'
					});
				} finally {
					this.loading = false;
				}
			},
			async getVuex(ee = false) {
				if (ee) { // 重置预加载数据当强制刷新时
					this.page = 1; // 从第1页开始
					this.data = [];
					this.total = null;
					this.status = 'loadmore';
					this.preloadData = {}; // 清空预加载缓存
				}
				const res = await this.preloadNextPage(ee ? 0 : this.page);
				this.data = ee ? res.data : [...this.data, ...res.data];
				this.status = res.total > this.page * this.pageSize ? 'loadmore' : 'nomore';
				this.page = res.page + 1;
				this.total = res.total;
				// 预加载下一页资源
				if (this.status === 'loadmore') {
					this.$nextTick(() => this.preloadNextPage(this.page));
				}
			},
			async preloadNextPage(currentPage) {
				if (this.preloadData[currentPage]) {
					return this.preloadData[currentPage]
				} else {
					this.loading = true;
					// article flow
					try {
						const res = await getScroll({
							custom: {
								auth: true,
								toast: false,
							},
							params: {
								page: currentPage, // 传递下一页页码
								pageSize: this.pageSize,
								type: this.type,
								list: 'true',
							}
						});
						// 预加载图片资源 
						if (res?.data && Array.isArray(res.data)) {
							res.data.forEach(item => {
								const img = new Image();
								img.src = uv_image(item);
								// img.onerror = () => console.error('图片预加载失败:', img.src);
							});
						}
						this.preloadData[currentPage] = res
						// 清理旧缓存（保留最近5页）
						const keys = Object.keys(this.preloadData).map(Number);
						if (keys.length > 5) {
							// 删除最旧的缓存（页码最小的）
							const minKey = Math.min(...keys);
							delete this.preloadData[minKey];
						}
						return res;
					} finally {
						this.loading = false;
					}
				}
			},
			async delx(i = '') {
				let newArray = this.data.slice();
				let ids = [];
				if (i) {
					ids[0] = i;
				} else {
					ids = this.ind;
				}
				if (await this.delVuex(ids))
					this.$emit('resid', ids);
			},
			async delVuex(i) {
				try {
					await delScroll({
						ids: i
					}, {
						custom: {
							auth: true,
							toast: false,
							catch: true,
						},
					})

					this.data = this.data.filter(item => !i.includes(item._id));

					// 关键修复：清空预加载缓存并重置状态
					this.preloadData = {};
					this.status = 'loadmore';

					// 如果当前页数据不足，自动加载更多
					if (this.data.length < this.pageSize && this.status === 'loadmore') {
						this.loadMore();
					}
					return true;
				} catch (error) {
					console.error('删除失败:', error);
					this.$refs.toast.show({
						message: error.msg || '删除失败，请重试',
						type: 'error',
						duration: 5000
					});
					return false;
				}
			},
			delOtherAll() {
				// let ids = this.data.filter(obj => obj._id !== this['vuex_' + this.type + '_id']).map(item => item._id);
				let ids = this.data.map(item => item._id);
				// let ids = this.data.findIndex(item => item._id !== this['vuex_' + this.type + '_id']);
				// this.$uv.vuex('vuex_' + this.type, [this['vuex_' + this.type][index]]);
				this.delVuex(ids);
			},
			select(id) {
				if (this.multiple) {
					let index = this.ind.findIndex(item => item === id);
					if (index >= 0) {
						this.ind.splice(index, 1);
					} else {
						this.ind.push(id);
					}
				} else {
					this.ind = [id];
				}
			},
			submit(e) {
				// var vuex_data = this['vuex_' + this.type];
				// console.log(JSON.stringify(this.vuex_data));
				this.ind = [e._id];
				this.$emit('submit', e._id);
			},
			routed(url) {
				uni.$uv.route({
					url: url,
					intercept(params, next) {
						// console.log(params, next)
						uni.showLoading({
							title: '等待中...'
						})
						// 模拟处理等待
						setTimeout(() => {
							uni.hideLoading();
							next(true);
						}, 1000)
					}
				})
			}
		}
	}
</script>

<style scoped lang="scss">
	@import "@/uni_modules/uv-ui-tools/index.scss";

	.chat-history {
		height: 100%;
		background-color: #fff;
		z-index: 4;

		.history_content {
			height: 20px;
			margin: 0px;
			padding: 0px;
			display: flex;
			justify-content: space-between;
			align-items: center;
		}

		.mid_m {
			height: calc(100% - 65px);
			overflow: auto;
		}

		.mid_d {
			height: calc(100% - 30px);
		}

		.footer_s {
			width: 100%;
			overflow: auto;
			display: flex;
			justify-content: space-around;
			align-content: flex-start;
			align-items: center;
			flex-wrap: wrap;
			position: relative;
			background-color: #fff;
			margin-bottom: 5px;
			margin-top: 5px;

			.footer_item {
				width: 120px;
				// height: auto;
				padding: 2px;
				margin: 0px;
				margin-top: 5px;
				border-radius: 6px;
				overflow: hidden;

				display: flex;
				justify-content: space-between;
				align-items: center;
				border: 2px solid #FFF;

				// word-break: break-all; // 允许单词内自动换行，如果一个单词很长的话
				// text-overflow: ellipsis; // 溢出用省略号显示
				// overflow: hidden; // 超出的文本隐藏
				// display: -webkit-box; // 作为弹性伸缩盒子模型显示
				// -webkit-line-clamp: 2; // 显示的行
				// -webkit-box-orient: vertical; // 设置伸缩盒子的子元素排列方式--从上到下垂直排列
				.opacity {
					opacity: 0;
				}

				.positionss {
					position: relative;
					display: flex;
					justify-content: space-between;
					align-items: center;
					width: 100%;
					background-color: #efefef;
					margin: 0px;
					padding: 0px;
				}
			}

			.footer_item:hover {
				background-color: #aaffff;
			}

			.activity {
				// background-color: #0000ff;
				border: 2px solid #333333;
			}
		}

		.multiple_h {
			display: flex;
			justify-content: space-between;
			align-items: center;
			opacity: 0.4;
			margin: 0px;
		}

		.multiple_activity {
			opacity: 1;
		}

	}
</style>